#!/bin/bash

echo Backup Unlocked Nexus One 1.0 - Ferran Busquets - ferranb@gmail.com
echo Note: root not required 

LOCAL_BACKUPS_DIR=$HOME/apps/android
SD_BACKUP_DIR=/sdcard/nandroid
SECONDS_SLEEP_SDCARD=10
FASTBOOT=`which fastboot`
RECOVERY=$HOME/apps/android/recovery-RA-passion-v2.2.1.img
ADB=`which adb`

[ -z "$ADB" ] && echo adb not found! && exit 1
[ -z "$FASTBOOT" ] && echo fastboot not found! && exit 1
[ -z "$RECOVERY" ] && echo recovery image not defined  && exit 1
[ ! -r "$RECOVERY" ] && echo recovery image not found: $RECOVERY && exit 1

echo Using local backup dir: $LOCAL_BACKUPS_DIR
echo Using recovery file: $RECOVERY
echo ... Please plug your Unlocked Nexus One 
echo ... Waiting for device. If the script hangs here, please ensure USB debugging is enabled, android is running and device is powered on ';-)'
$ADB wait-for-device
echo ... Rebooting to bootloader
$ADB reboot bootloader
echo ... Booting as recovery image
sudo $FASTBOOT boot $RECOVERY
echo ... Waiting for recovery image load
while [ -z `$ADB shell pwd 2> /dev/null` ]
do
  sleep 1
done
echo ... Backing up
$ADB shell nandroid-mobile.sh --backup --defaultinput --norecovery
echo ... Mountiing sdcard
$ADB shell mount sdcard
echo ... Syncing sd backups with local disk
echo ... Looking for backups
TERMINAL_BACKUP_DIR=$SD_BACKUP_DIR/`$ADB get-serialno`
for dir in `$ADB shell ls $TERMINAL_BACKUP_DIR`
do
  dir=`echo $dir | tr -d '\r' | tr -d '\n'`
  echo ... Terminal backup directory found: $dir
  TARGET=$LOCAL_BACKUPS_DIR/${dir}
  echo ... ... Looking for local $TARGET
  if [ -d $TARGET ]
  then
    echo ... ... Local directory exists, skipping
  else
    echo ... ... Local directory does not exists, pulling
    $ADB pull $TERMINAL_BACKUP_DIR/$dir $LOCAL_BACKUPS_DIR/$dir
    echo ... ... Checking MD5sums
    md5sum --check nandroid.md5 --status
  fi 
done
#echo ... Umounting sdcard
$ADB shell sync
#$ADB shell mount sdcard
echo ... Reeboting device
$ADB shell reboot
echo ... Backup done
# To restore just execute the following:
# fastboot flash userdata data.img 
# fastboot flash system system.img 
# fastboot flash boot boot.img 
# fastboot reboot 
